import { observable, action } from 'mobx'
import http from 'utils/http'

async function getNav(type = 'footer') {
  const path = type === 'footer' ? 'nav/list' : 'indexNav/list'
  const res = await http.get(path)
  if (res.code === 1) {
    return res.data.data
  }
  throw new Error(res.info)
}

function leftPadZero(val) {
  if (val < 10) {
    return `0${val}`
  }
  return val.toString()
}

function random(array) {
  return array[Math.floor(Math.random() * array.length)]
}

function randomRange(min, max) {
  return Math.floor((Math.random() * (max - min)) + min)
}

function formatDate(month, date, hour, min) {
  return `${leftPadZero(month)}-${leftPadZero(date)} ${leftPadZero(hour)}:${leftPadZero(min)}`
}

function createDate() {
  const date = new Date()
  const curDate = date.getDate()
  const curMounth = date.getMonth() + 1

  const dates = [curDate - 1, curDate - 2, curDate - 3]
  // 8-22小时，且小于当前的时间
  const hours = [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
  const randomDate = random(dates)
  const randomHour = random(hours)
  const randomMin = Math.floor(Math.random() * 60)

  return formatDate(curMounth, randomDate, randomHour, randomMin)
}

function createMobile() {
  const prefixAry = [130, 131, 134, 135, 136, 138, 170, 180, 182, 185, 186, 187, 189]
  const prefix = random(prefixAry)
  const after = randomRange(1000, 9999)
  return `${prefix}****${after}`
}

function createMoney() {
  const moneyAry = [1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000]
  return random(moneyAry)
}

function createScrollAd(list) {
  const ret = []
  for (let i = 0; i < 20; i += 1) {
    ret.push({
      ...list[i],
      date: createDate(),
      mobile: createMobile(),
      money: createMoney(),
    })
  }
  return ret
}

class MsiteStore {
  @observable footerNavList = []
  @observable indexNavList = []
  @observable scrollAdList = []

  @action
  async getFooterNav() {
    const footerNavList = await getNav('footer')
    this.footerNavList = footerNavList
  }

  @action
  async getIndexNav() {
    const indexNavList = await getNav('index')
    this.indexNavList = indexNavList
  }

  @action
  async getScrollAd() {
    const res = await http.get('advert/list', { page: 1, pageSize: 60 })
    if (res.code === 1) {
      this.scrollAdList = createScrollAd(res.data.data)
    }
  }
}


const msiteStore = new MsiteStore()

export default msiteStore
export { MsiteStore }
